package newcoder_exp.justPractise;
import java.util.*;
import org.junit.*;
import tree.*;
public class NC46 {

    public class Solution {
        public boolean isSymmetric (TreeNode root) {
            if (root == null) return true;
            Queue<TreeNode> queue = new LinkedList<>();
            Deque<TreeNode> deque;
            TreeNode cur;
            queue.offer(root);
            int n = 0;
            while (!queue.isEmpty()) {
                n = queue.size();
                deque = new LinkedList<>(queue);
                for (int i = 0; i < n / 2; i++) {
                    if (deque.peekFirst() == null && deque.peekLast() == null) {
                        continue;
                    }
                    if (deque.peekFirst() == null && deque.peekLast() != null
                    || deque.peekFirst() != null && deque.peekLast() == null) {
                        return false;
                    } else if (deque.peekFirst().val != deque.peekLast().val) {
                        return false;
                    }
                    deque.pollFirst();
                    if (!deque.isEmpty())
                        deque.pollLast();
                }
                for(int i = 0; i < n; i++) {
                    cur = queue.poll();
                    if (cur == null) {
                        continue;
                    }
                    if (cur.left != null) {
                        queue.offer(cur.left);
                    } else {
                        queue.offer(null);
                    }
                    if (cur.right != null) {
                        queue.offer(cur.right);
                    } else {
                        queue.offer(null);
                    }
            }
        }
        return true;
    }

    @Test
public void test() {
    Solution s = new Solution();
    // int[] nums = new int[]{};
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(2);
    root.right = new TreeNode(2);
    boolean res = s.isSymmetric(root);
    System.out.println(res);
}
}





    public boolean isSymmetric2 (TreeNode root) {
        if (root == null) return true;
        return help(root.left, root.right);
    }

    public boolean help (TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        else if (left == null || right == null) return false;

        return help(left.left, right.right) && help(left.right, right.left);
    }

    public boolean isSingle(TreeNode node) {
        return node.left == null && node.right == null;
    }
    

    @Test
    public void test() {
        // int[] nums = new int[]{};
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(2);
    }

}

